using System;
using System.Web.Caching;
using System.Web.UI;

namespace Rioshu.Web.ViewStateHandlers
{
    public class WebCachePersister : IViewStateHandlersPersister
    {
        public CachePersisterConfigurationHandler Configuration
        {
            get; set;
        }

        public WebCachePersister()
        {
            Configuration = CachePersisterConfigurationHandler.GetConfiguration();
        }

        #region IViewStateHandlersPersister Members

        public void SaveState(Page page, Pair pageState)
        {
            string id = Guid.NewGuid().ToString();
            page.Cache.Insert(id, pageState, null, Cache.NoAbsoluteExpiration, Configuration.SlideTime);
            page.ClientScript.RegisterHiddenField(Configuration.FieldName, id);
        }

        public Pair LoadState(Page page)
        {
            string id = page.Request.Form[Configuration.FieldName];
            var pageState = page.Cache.Get(id) as Pair;
            if (pageState == null) throw new InvalidOperationException("There is no such page state in the cache");
            return pageState;
        }

        #endregion
    }
}